using System.Collections.Generic;
using Microsoft.Xna.Framework.Graphics;

namespace Babylon.Toolbox
{
    partial class StatesManager
    {
        int currentDepthStencilKey = -1;
        bool depthBufferEnable = true;
        bool depthBufferWrite = true;
        readonly Dictionary<int, DepthStencilState> depthStencilStates = new Dictionary<int, DepthStencilState>();

        public bool DepthBufferEnable
        {
            get { return depthBufferEnable; }
            set
            {
                depthBufferEnable = value;
            }
        }

        public bool DepthBufferWrite
        {
            get { return depthBufferWrite; }
            set
            {
                depthBufferWrite = value; 
            }
        }

        int ComputeDepthStencilKey()
        {
            return ((depthBufferEnable ? 1 : 0) << 1) + (depthBufferWrite ? 1 : 0);
        }

        public void ApplyDepthStencilState()
        {
            int key = ComputeDepthStencilKey();

            if (key == currentDepthStencilKey)
                return;

            DepthStencilState depthStencilState;

            if (!depthStencilStates.TryGetValue(key, out depthStencilState))
            {
                depthStencilState = new DepthStencilState
                                        {
                                            DepthBufferEnable = depthBufferEnable,
                                            DepthBufferFunction = CompareFunction.LessEqual,
                                            DepthBufferWriteEnable = DepthBufferWrite
                                        };

                depthStencilStates.Add(key, depthStencilState);
            }

            currentDepthStencilKey = key;
            Device.DepthStencilState = depthStencilState;
        }
    }
}
